<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="./css/index.css">
    <script src="./js/jquery.min.js"></script>
    <script src="./js/template-web.js"></script>
</head>

<body>
    <div class="container">
        <img src="./img/01.png" alt="" class="logo" />

        <div class="box">
            <div class="tabs">
                <div class="tab-active">宝贝</div>
                <div class="tab-dian">店铺</div>
            </div>
            <div class="sous">
                <input type="text" placeholder="请输入要搜索的内容" id="ipt">
                <button class="sou">搜索</button>
            </div>
            <!-- 搜索建议列表 -->
            <div id="suggest-list"></div>
        </div>
    </div>

    <!-- 模板结构 -->
    <script type="text/html" id="tpl-suggestList">
        {{each result}}
        <!-- 搜索建议项 -->
        <div class="suggest-item">{{$value[0]}}</div>
        {{/each}}
    </script>

    <script>
        $(function() {
            // 定义延时器的id
            var timer = null;
            // 定义全局缓存对象
            var cacheObj = {};
            // 定义防抖函数
            function debounce(kw) {
                timer = setTimeout(function() {
                    getSuggest(kw)
                }, 500)
            }

            // 为输入框绑定keyup事件
            $('#ipt').on('keyup', function() {
                    clearTimeout(timer);
                    var keywords = $(this).val().trim()
                    if (keywords.length <= 0) {
                        return $('#suggest-list').empty().hide()
                    }
                    // 先判断缓存里有数据
                    if (cacheObj[keywords]) {
                        return render(cacheObj[keywords]);
                    }

                    // 获取搜索建议
                    // getSuggest(keywords);

                    debounce(keywords);
                })
                // 获取查询列表事件
            function getSuggest(kw) {
                $.ajax({
                    url: 'http://suggest.taobao.com/sug?q=' + kw,
                    dataType: 'jsonp',
                    success: function(res) {
                        render(res);
                    }
                })
            }
            // 渲染ui结构
            function render(res) {
                if (res.result.length <= 0) {
                    return $('#suggest-list').empty().hide()
                }
                var htmlStr = template('tpl-suggestList', res);
                $('#suggest-list').html(htmlStr).show()

                // 获取到用户输入的内容，当作键
                var k = $('#ipt').val().trim()
                    // 需要将数据作为值，进行缓存
                cacheObj[k] = res;
            }


        })
    </script>


</body>

</html>